
package com.e885.util.web;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Grady.Kao
 * @version 1.0
 * @company E885 Group
 * @copyright Copyright (c) 2000-2008
 */

public class Report
{
	/**
	 * exception report
	 * 
	 * @param buffer
	 * @param throwable
	 */
	public void exceptionReport( StringBuffer buffer, Throwable throwable )
	{
		buffer.append( "\n" );
		
		StringWriter writer = new StringWriter();

		throwable.printStackTrace( new PrintWriter( writer ) );

		buffer.append( writer.getBuffer() );
	}

	/**
	 * request report
	 * 
	 * @param buffer
	 * @param request
	 */
	public void requestReport( StringBuffer buffer, HttpServletRequest request )
	{
		buffer.append( "\n" );
		requestURLReport( buffer, request );
		
		buffer.append( "\n" );
		requestSessionIdReport( buffer, request );
	}
	
	/**
	 * about url report
	 * @param buffer
	 * @param request
	 */
	private void requestURLReport( StringBuffer buffer, HttpServletRequest request )
	{
		buffer.append( "Request:" );
		buffer.append( request.getMethod() );
		buffer.append( " " );
		buffer.append( request.getRequestURL() );

		String queryString = request.getQueryString();
		if( queryString != null )
		{
			buffer.append( "?" );
			buffer.append( queryString );
		}
	}

	/**
	 * about cookie report
	 * 
	 * @param buffer
	 * @param request
	 */
	private void requestSessionIdReport( StringBuffer buffer, HttpServletRequest request )
	{
		buffer.append( "Session ID:" );
		
		String sessionId = request.getRequestedSessionId();
		
		if( sessionId == null )
			buffer.append( "none" );
		else
		{
			if( request.isRequestedSessionIdValid() )
			{
				buffer.append( sessionId );
				buffer.append( "(from " );
				
				if( request.isRequestedSessionIdFromURL() )
					buffer.append( "url" );
				else if( request.isRequestedSessionIdFromCookie() )
					buffer.append( "cookie" );
				else
					buffer.append( "unkown" );
				
				buffer.append( ")" );
			}
			else
			{
				buffer.append( "invalid" );
			}
		}
	}
}
